package com.tanhua.mongo.service;

import com.tanhua.model.mongo.Friend;
import com.tanhua.model.mongo.Movement;
import com.tanhua.model.mongo.MovementTimeLine;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

@Component
public class MovementTimeLineService {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Async
    public void saveTimeLine(Movement movement) {

        // 查询当前用户的好友
        List<Friend> friendList = mongoTemplate.find(new Query(
                Criteria.where("userId").is(movement.getUserId())
        ), Friend.class);

        // 遍历好友列表数据，添加时间线数据
        for (Friend friend : friendList) {
            MovementTimeLine movementTimeLine = new MovementTimeLine();
            movementTimeLine.setMovementId(movement.getId());
            movementTimeLine.setCreated(new Date().getTime());
            movementTimeLine.setFriendId(friend.getFriendId());
            movementTimeLine.setUserId(friend.getUserId());

            mongoTemplate.save(movementTimeLine);
        }

    }

}
